<script setup lang='ts'>
import {nextTick, reactive, ref} from 'vue';
import {propApi} from '@/api/controller';
import {ToastSuccess, ToastWarning, Toastloading, allNumber} from '@/utils/public';
import Pagination from "@/components/Pagination/index.vue";
import {ElMessageBox} from 'element-plus';
import inventory from './inventory.vue';
import poolConfigList from './poolConfigList.vue';
import {counterClassify} from "@/pinia/getter";
import serachRoomid from "@/components/serachRoomid/index.vue"

const formLabelWidth = '140px'
const dataForm = ref(),
  inventoryRef = ref(),
  poolConfigListRef = ref()
const $emit = defineEmits(['updateList'])


interface roomFormInterface {
  roomUUID: string,
  roomID: string,
  cate_id: string,
  list: {
    total:0,
    list: [],
  },
}

let roomForm = ref({
  roomUUID: '',
  roomID: '',
  cate_id: '',
  list: {
    total:0,
    list: [],
  },
} as roomFormInterface);


interface dialogInterface {
  roomDialog: boolean,
}

let dialog = ref({
  roomDialog: false,
} as dialogInterface);


const action = reactive({
  title: '',
  formTitle: '',
  dialogTableVisible: false,
  dialogFormVisible: false,
  disabled: false,
  total: 0,
  list: [] as Array<any>,
})
const listQuery = reactive({
  page: 1,
  limit: 20,
  gift_id: 0,
})

const roomListQuery = reactive({
  page: 1,
  limit: 20,
})


interface formQuert {
  gift_id: number
  pool_id: number
  pool_name: string
  min_count: number
  max_count: number
  hours: number
  // rate:number
}

let form = reactive({} as formQuert)
const formRules = {
  pool_name: [{required: true, trigger: "blur", message: "请输入礼物池名称"}],
  min_count: [{required: true, trigger: "blur", message: "请输入最小参与数"}],
  max_count: [{required: true, trigger: "blur", message: "请输入最大参与数"}],
  hours: [{required: true, trigger: "blur", message: "请输入间隔时间(小时)"}],
  // rate: [{ required: true, trigger: "blur", message: "请输入整数礼物外显概率" }],
}
const handleForm = (row: any = {}) => {
  const {id = '', pool_name = '', min_count = '', max_count = '', hours = '', out_rate = '',} = row
  action.formTitle = id ? '编辑礼物池礼物' : '新增礼物池礼物'
  const query = {} as formQuert
  if (id) {
    query['pool_id'] = id
    query['pool_name'] = pool_name
    query['min_count'] = min_count
    query['max_count'] = max_count
    query['hours'] = hours
    // query['rate'] = out_rate * 100
  } else {
    query['gift_id'] = listQuery.gift_id
  }
  Object.assign(form, query)
  action.dialogFormVisible = true
}
const handleConfig = (row: any = {}) => {
  poolConfigListRef.value.openDialog(row)
}
/**
 * 新增/编辑配置
 */
const handleFormSubmit = () => {
  dataForm.value.validate(async (valid: any) => {
    if (!valid) return
    const {pool_id = 0} = form
    let submitSet = false
    const loading = Toastloading()
    if (pool_id) {
      await propApi.editeastereggPrizePools(form).then(() => {
        ToastSuccess('编辑礼物池成功')
        submitSet = true
      }).catch(() => {
        loading.close()
      })
    } else {
      await propApi.seteastereggPrizePools(form).then(() => {
        ToastSuccess('新增礼物池成功')
        submitSet = true
      }).catch(() => {
        loading.close()
      })
    }
    if (submitSet) {
      loading.close()
      getList()
      closeFormDialog()
    }
  })
}
const handleReset = (row: any = {}) => {
  const {pool_name = '', id = 0} = row
  ElMessageBox.confirm(`确定更新礼物池：${pool_name}吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const loading = Toastloading();
      await propApi.colorGiftPoolReset({
        pool_id:id,
      });
      loading.close();
      ToastSuccess('更新成功');
      getList();
    })
    .catch(() => {});
  }
  const handleClose = (row:any = {})=>{
    const { pool_name='', id=0, is_open=-1 } = row
    if(is_open < 0) return ToastWarning('is_open 参数异常')
    const title = ['','礼物池关闭','礼物池开启'][is_open]
    ElMessageBox.confirm(`确定${title}：${pool_name}吗?`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      const loading = Toastloading();
      await propApi.colorGiftSetPoolStatus({
        pool_id:id,
        pool_status:['',2,1][is_open]
      });
      loading.close();
      ToastSuccess(`${title}成功`);
      getList();
    })
    .catch(() => {
    });
}
const getList = async () => {
  const loading = Toastloading()
  const res = await propApi.geteastereggPrizePoolsList(listQuery)
  loading.close()
  const {data = [], total = 0} = res.data
  action.total = total
  action.list = data
}
const openDialog = async (query: any = {}) => {
  const {gift_id = 0, name = ''} = query
  listQuery.gift_id = gift_id
  action.title = `${name}-礼物礼物池`
  const loading = Toastloading()
  await getList()
  loading.close()
  action.dialogTableVisible = true
}
const closeDialog = () => {
  action.dialogTableVisible = false
}
const closeFormDialog = () => {
  form = reactive({} as formQuert)

  nextTick(() => {
    dataForm.value.clearValidate();
  });
  action.dialogFormVisible = false
}

const handleRoom = (row: any) => {
  dialog.value.roomDialog = true;
  getRoomList();
}

const getRoomList = async () => {
  let list = await propApi.getRoomList(roomListQuery);
  roomForm.value.list = list.data.data;
}

  defineExpose({
    openDialog
  })
</script>

<template>
  <div>
    <el-dialog
    top="5vh"
    class="xm-dialog "
    v-model="action.dialogTableVisible"
    width="75%"
    :title="action.title">
      <div class="xm-headTab">
        <div class="labelBox">
          <div class="labelItem">
            <el-button type="primary" @click="getList">查询</el-button>
            <el-button type="primary" @click="handleForm">新增礼物池</el-button>
          </div>
        </div>
      </div>
      <!-- <el-button class="xm-mb10 xm-mrAuto" type="primary" @click="handleForm()">新增</el-button> -->
      <el-table
        class="xm-main xm-TableCenter"
        :data="action.list"
        border
      >
        <el-table-column width="80" prop="id" label="礼物池ID" />
        <el-table-column min-width="180" prop="pool_name" label="礼物池名称" />
        <el-table-column sortable width="140" prop="min_count" label="最小参与次数" />
        <el-table-column sortable width="140" prop="max_count" label="最大参与次数" />
        <el-table-column sortable width="150" prop="hours" label="间隔时间(小时)">
          <template #default="scoped">
            {{ scoped.row.hours}}h
          </template>
        </el-table-column>
        <!-- <el-table-column sortable width="120" prop="out_rate" label="外显概率">
          <template #default="scoped">
            {{ scoped.row.out_rate * 100 }}%
          </template>
        </el-table-column> -->
        <el-table-column min-width="100" prop="is_open" label="礼物池状态">
          <template #default="scoped">
            {{ ['','开启','关闭'][scoped.row.is_open] || scoped.row.is_open }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" width="380" label="操作">
          <template #default="scoped">
            <el-row>
              <el-col :span="24">
                <el-button type="primary" @click="handleForm(scoped.row)">编辑礼物池</el-button>
                <el-button type="primary" @click="handleReset(scoped.row)">更新礼物池</el-button>
<!--                <el-button type="primary" @click="handleRoom(scoped.row)">房间奖池设置</el-button>-->
              </el-col>
              <el-col :span="24" class="xm-mt10">
                <el-button type="primary" @click="handleConfig(scoped.row)">礼物池配置</el-button>
                 <el-button type="primary" @click="inventoryRef.openDialog(scoped.row)">礼物池剩余数量</el-button>
                <el-button
                :type="['','warning','success'][scoped.row.is_open]"
                @click="handleClose(scoped.row)"
                >{{ ['','关闭礼物池','开启礼物池'][scoped.row.is_open] }}</el-button>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <Pagination v-show="action.total > 0" :total="action.total" v-model:page="listQuery.page"
      v-model:limit="listQuery.limit" @pagination="getList" />
      <!-- <template v-if="!action.disabled" #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template> -->
    </el-dialog>
    <el-dialog
      top="10vh"
      class="xm-dialog input-width"
      v-model="action.dialogFormVisible"
      :close-on-click-modal="action.disabled"
      :show-close="action.disabled"
      :close-on-press-escape="action.disabled"
      width="35%"
      :title="action.formTitle">
      <el-form ref="dataForm" :model="form" :rules="formRules">
        <el-form-item :label-width="formLabelWidth" label="礼物池名称" prop="pool_name">
          <el-input v-model="form.pool_name" placeholder="请输入礼物池名称"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="间隔时间(小时)" prop="hours">
          <el-input v-model="form.hours" @input="allNumber(form,'hours')" placeholder="请输入间隔时间(小时)"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="最小参与数" prop="min_count">
          <el-input v-model="form.min_count" @input="allNumber(form,'min_count')" placeholder="请输入最小参与数"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="最大参与数" prop="max_count">
          <el-input v-model="form.max_count" @input="allNumber(form,'max_count')" placeholder="请输入最大参与数"/>
        </el-form-item>
        <!-- <el-form-item :label-width="formLabelWidth" label="外显礼物概率" prop="rate">
          <el-input v-model="form.rate" @input="allNumber(form,'rate')" placeholder="请输入整数礼物概率"/>
        </el-form-item> -->
      </el-form>
      <template v-if="!action.disabled" #footer>
        <span class="dialog-footer">
          <el-button @click="closeFormDialog">取 消</el-button>
          <el-button type="primary" @click="handleFormSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!--房间奖池设置-->
    <el-dialog
      top="10vh"
      class="xm-dialog input-width"
      v-model="dialog.roomDialog"
      style="width:calc(100vw - 400px);height:calc(100vh - 200px);"
      title="房间奖池设置">
      <div style="height:100%;">
        <div>
          <div class="labelBox">
            <div class="labelItem">
              <div class="label">房间UUID：</div>
              <serachRoomid v-model:room_uid="roomForm.roomUUID"/>
            </div>
            <div class="labelItem">
              <div class="label">房间ID：</div>
              <el-input type="text" style="width:100px;" placeholder="请输入房间ID" v-model="roomForm.roomID"/>
            </div>
            <div class="labelItem">
              <div class="label">筛选：</div>
              <el-select v-model="roomForm.cate_id" placeholder="请选择游戏">
                <el-option label="公池" value="1"/>
                <el-option label="房间个池" value="2"/>
              </el-select>
            </div>
            <div class="labelItem">
              <el-button type="primary" @click="">查询</el-button>
            </div>
          </div>
        </div>
        <el-table
          class="room"
          :data="roomForm.list.list"
          border
          height="calc(100vh - 500px)"
        >
          <el-table-column sortable prop="UUID" label="房间UUID"/>
          <el-table-column prop="room_name" label="房间名"/>
          <el-table-column sortable label="所属奖池">
            <template #default="scoped">
              <el-row>
                <el-col v-if="scoped.row.cate_id=='1'">
                  公池
                </el-col>
                <el-col v-if="scoped.row.cate_id=='2'">
                  房间个池
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column fixed="right" width="180" label="操作">
            <template #default="scoped">
              <el-row>
                <el-col :span="24">
                  <el-button v-if="true" type="primary" @click="handleForm(scoped.row)">生成房间</el-button>
                  <el-button v-if="false" type="danger" @click="handleReset(scoped.row)">拉入公池</el-button>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
        <Pagination v-show="roomForm.list.total > 0" :total="roomForm.list.total" v-model:page="roomListQuery.page" v-model:limit="roomListQuery.limit" @pagination="getRoomList"/>
      </div>
    </el-dialog>
    <inventory ref="inventoryRef"/>
    <poolConfigList ref="poolConfigListRef"/>
  </div>
</template>
